<?php

namespace app\common\model;

use app\common\exception\BusinessException;
use app\common\service\UserService;

class OrderBonusItem extends Base
{
    /**
     * 开启自动时间戳
     * @var bool
     */
    protected $autoWriteTimestamp = false;

    /**
     * changeByOrderId
     * @param $order_id
     * @throws
     */
    public function changeByOrderId($order_id)
    {
        // 查询订单信息
        $order = app(Order::class)->find($order_id);
        if (!$order || !$order['user_id'] || !$order['order_price'] || $order['status'] != 4) {
            $this->clearItemByOrderId($order_id);
            return;
        }

        // 查询关联上级信息
        $allParent = app(AgentRelation::class)->getAllParentByChildUid($order['user_id']);
        if (!$allParent) {
            $this->clearItemByOrderId($order_id);
            return;
        }

        // 查询上级分红比例配置
        $allParentUid = array_column($allParent, 'parent_uid');
        $allParentUser = app(UserService::class)->getAgentByAllUid($allParentUid);
        $allParentDict = array_dict($allParentUser, 'id');

        // 循环生成分红明细
        foreach ($allParent as $parent) {
            // 提取参数
            $parent_id = $parent['parent_uid'];
            $relation_level = $parent['relation_level'];

            // 提取分红比例
            $parentBonusRateOne = $allParentDict[$parent_id]['bonus_rate_one'] ?? 0;
            $parentBonusRateTwo = $allParentDict[$parent_id]['bonus_rate_two'] ?? 0;

            // 计算分红金额
            $order_amount = $order['order_price'];
            $parentBonusRate = $relation_level == 1 ? $parentBonusRateOne : $parentBonusRateTwo;
            $parentBonusAmount = $order_amount * $parentBonusRate / 100;
            $parentBonusAmount = truncateDecimal($parentBonusAmount);

            // 保存数据
            $saveData = [
                'order_id' => $order_id,
                'agent_id' => $parent_id,
                'order_amount' => $order_amount,
                'bonus_rate' => $parentBonusRate,
                'bonus_amount' => $parentBonusAmount,
                'relation_level' => $relation_level,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ];

            // 查询是否存在
            $where = [
                'order_id' => $order_id,
                'agent_id' => $parent_id,
            ];
            $count = $this->where($where)->count();
            if (!$count) {
                $isAdd = $this->add_data($saveData);
                if (!$isAdd) {
                    throw new BusinessException('新增分红明细失败');
                }
            } else {
                unset($saveData['create_time']);
                $isSave = $this->save_data($saveData, $where);
                if (!$isSave) {
                    throw new BusinessException('保存分红明细失败');
                }
            }
        }
    }

    /**
     * clearItemByOrderId
     * @throws BusinessException
     */
    private function clearItemByOrderId($order_id)
    {
        // 查询条件
        $where = [['order_id', '=', $order_id]];

        // 更新数据
        $saveData = [
            'status' => 2,
        ];
        $isUpdate = $this->save_data($saveData, $where);
        if ($isUpdate === false) {
            throw new BusinessException('更新分红明细失败');
        }
    }
}